package com.softeem.spider;

import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 日志工具
 */
public class LogUtils {

    private static final String mid_dir = "/spider_logs";

    /**
     * 获取桌面文件对象
     * @return
     */
    private static File getDesktopFile() {
        FileSystemView fsv = FileSystemView.getFileSystemView();
        File home = fsv.getHomeDirectory();
        return home;
    }

    /**
     * 生成日志文件（以日期为文件名）
     * @return
     */
    private static File genLogFile(){
        File dir = new File(getDesktopFile(),mid_dir);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //准备日志文件
        File file = new File(dir, LocalDate.now().toString() + ".log");
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return file;
    }

    /**
     * 写入日志
     * @param msg
     */
    public static void log(String msg) {
        //获取日志时间
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //拼接日志内容
        String content = "【" + time + "】" + msg +"\r\n";
        try (
            FileOutputStream fos = new FileOutputStream(genLogFile(),true);
            ){
            //写入文件
            fos.write((content).getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
